<?php
namespace app\mobile\controller;
use cmf\controller\HomeBaseController;
use app\portal\model\UserRankModel;
use app\portal\model\UserOrganizeModel;
use app\portal\model\PointExchangeLogModel;
use app\portal\model\UserModel;
use think\Db;
use Firebase\JWT\JWT;

class PersonalController extends WechatController
{

    public function initialize(){
        parent::initialize();
        $this->user_id=1;
        //$this->user_id=cmf_get_current_user_id();
//        $sel=Db::name('user_organize')->where('user_id',$this->user_id)->where('status',1)->select();
//        if (count($sel)==0){
//            /**根据是否已经是志愿者判断能不能看这个页面*/
//            $this->redirect('/mobile/user/apply');
//        }
    }

    /**个人中心*/
    public function personal(){
        return $this->fetch('personal');
    }
    /** 新闻详情 */
    public function detail(){
        $id= input('id');
        $article = Db::name('portal_post')->where('id',$id)->find();
        $article['post_content']=str_replace("default","/upload/default",$article['post_content']);
        //dump($article);
        $this->assign('article',$article);
        return $this->fetch();
    }
    /** 公益日记*/
    public function riji(){
        return $this->fetch('gongyi_riji');
    }
    /** 公益时间*/
    public function time(){
        return $this->fetch('gongyi_time');
    }

    /** 我的积分*/
    public function jifen(){
        return $this->fetch();
    }

    /** 申请活动*/
    public function apply_activity(){
        return $this->fetch();
    }

    /** */
    public function weixin(){
        return $this->fetch();
    }

    public function index()
    {

        $model = new UserRankModel();
        $log = new PointExchangeLogModel();
        $list=$log->with('goods')->where('user_id',$this->user_id)->order('id desc')->select();
        $data=$model->with('user')->where('user_id',$this->user_id)->find();
        if(!$data){
            $model->insert(['user_id'=>$this->user_id]);
            $data=$model->with('user')->where('user_id',$this->user_id)->find();
        }
        $data['hour']=number_format($data['duration']/60,1);
        $points=Db::name('exchange_goods')->where(['status'=>1,'type'=>1])->select();
        $goods=Db::name('exchange_goods')->where(['status'=>1,'type'=>0])->select();

        $this->assign('goods',$goods);
        $this->assign('points',$points);
        $this->assign('data',$data);
        $this->assign('list',$list);
        return $this->fetch();
    }
    //修改信息
    public function change_info(){
        $user_model=new UserModel();
        $user=$user_model->with('groups')->with('communities')->where('id',$this->user_id)->find();
        unset($user['user_pass']);
        //$more=json_decode($user['more'],true);
        $car_info=Db::name('user_info')->where('user_id',$user['id'])->find();
        $group=Db::name('organize_child')->select();
        //dump($car_info);
        $sex=['','男','女'];
        $this->assign('sex',$sex);
        $this->assign('group',$group);
        $this->assign('user',$user);
        $this->assign('more',$user['more']);
        $this->assign('car_info',$car_info);
        return $this->fetch();
    }
    //积分兑换
    public function exchange(){
        $result=[];
        $result['msg']='接口维护中！';
        return $result;
        $id=input('id');
        $user_id=$this->user_id;
        $goods=Db::name('exchange_goods')->where('id',$id)->find();
        $find=Db::name('user_rank')->where('user_id',$user_id)->find();
        //判断兑换权限,剩余积分，车辆信息状态
        $car_info=Db::name('user_info')->where('user_id',$user_id)->find();

        if($goods['point']>$find['can_points']){
            $result['msg']='积分不足以兑换该商品';
            return $result;
        }
        if($goods['type']==1){
            $begin_year = strtotime(date("Y",time())."-1"."-1"); //本年开始
            $end_year = strtotime(date("Y",time())."-12"."-31"); //本年结束
            //需要验证车辆信息
            if(count($car_info)==0){
                $result['msg']='请先完善车辆信息';
                return $result;
            }
            $arr=[$begin_year,$end_year];
//            dump($arr);
            $points=Db::name('point_exchange_log')->where('user_id',$user_id)->where('goods_id','in',[1,2,3])->where('ctime','between',$arr)->sum('point');
            if($points+$goods['point']>24){
                $result['msg']='一自然年周期最多兑换24分！';
                return $result;
            }
            $key = "rzjj";
            $token = [
                "iss"=>"shuker",
                "aud"=>"",
                "iat" => time(),
                "nbf" => time(),
                "exp" => time()+60*60*24*366,
                'car_num'=>$car_info['car_card']
            ];
            $jwt=new JWT;
            $check_code =$jwt->encode($token,$key,"HS256");
            $array=['user_id'=>$user_id,'code'=>$check_code,'point'=>$goods['point'],'ctime'=>time(),'goods_id'=>$id];
            Db::startTrans();
            try{
                $id=Db::name('point_exchange_log')->insertGetId($array);
                Db::name('user_rank')->where('user_id',$user_id)->setInc('used_points',$goods['point']);
                Db::name('user_rank')->where('user_id',$user_id)->setDec('can_points',$goods['point']);
                $token['uid']=$id;
                $token['code']=$check_code;
                $res=$this->test($key,$token);
                if($res['err_code']==0){
                    throw new \Exception($res['msg']);
                }else{
                    Db::commit();
                    $result['msg']='兑换成功';
                }
            }catch (\Exception $e){
                $result['msg']='兑换失败';
                Db::rollback();
            }
        }else{
            Db::startTrans();
            try{
                $data=['user_id'=>$user_id,'point'=>$goods['point'],'ctime'=>time(),'goods_id'=>$id,'code'=>uniqid()];
                Db::name('point_exchange_log')->insert($data);
                Db::name('user_rank')->where('user_id',$user_id)->setInc('used_points',$goods['point']);
                Db::name('user_rank')->where('user_id',$user_id)->setDec('can_points',$goods['point']);
                Db::commit();
                $result['msg']='兑换成功';
            }catch (\Exception $e){
                $result['msg']='兑换失败';
                Db::rollback();
            }

        }

        return $result;
    }
    //删除积分记录
    public function log_del(){
        $result=[];
        try{
            $id= input('id');
            if(!$id){
                throw new \Exception('缺少参数~');
            }
            $Model = new PointExchangeLogModel();
            $Model->where('id',$id)->delete();
            $result["error"]= false;
            $result['errmsg']='success';
        }catch (\Exception $e){
            $result["error"]= true;
            $msg= "[{$e->getLine()}]".$e->getMessage();
            $result['errmsg']=$msg;
        }
        return json($result);
    }
    public function point_log_detail(){
        $log = new PointExchangeLogModel();
        $list=$log->with('goods')->where('user_id',$this->user_id)->order('id desc')->select();
        $this->assign('list',$list);
        return $this->fetch();
    }

    public function logout()
    {
        Db::name('user')->where('id',$this->user_id)->update(['openid'=>null]);//解除openid 与 user绑定
        session("user", null);//清除缓存
        return redirect("/mobile");
    }

}
